﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Reviewer.Utilities
{
    /// <summary>
    /// Enumeration utilities
    /// </summary>
    public static class EnumUtility
    {
        /// <summary>
        /// Tries the parse.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="input">The input.</param>
        /// <param name="result">The result.</param>
        /// <returns></returns>
        public static bool TryParse<T>(string input, out T result) where T : struct // error CS0702: Constraint cannot be special class 'System.Enum'
        {
            return TryParse<T>(input, out result, false);
        }

        /// <summary>
        /// Tries the parse.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="input">The input.</param>
        /// <param name="result">The result.</param>
        /// <param name="ignoreCase">if set to <c>true</c> [ignore case].</param>
        /// <returns></returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#",  Justification="TryParse method design")]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        public static bool TryParse<T>(string input, out T result, bool ignoreCase) where T : struct // error CS0702: Constraint cannot be special class 'System.Enum'
        {
            result = default(T);
            try
            {
                result = (T)Enum.Parse(typeof(T), input, ignoreCase);
                return true;
            }
            catch { }

            return false;
        }

        /// <summary>
        /// Tries the parse.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="input">The input.</param>
        /// <param name="result">The result.</param>
        /// <param name="defaultValue">The default value.</param>
        /// <returns></returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#", Justification = "TryParse method design")]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
        public static bool TryParse<T>(int input, out T result, T defaultValue) where T : struct// error CS0702: Constraint cannot be special class 'System.Enum'
        {
            result = defaultValue;
            try
            {
                result = (T)Enum.ToObject(typeof(T), input);
                return true;
            }
            catch { }

            return false;
        }
    }

}
